package com.clouddot.baipai.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIUrgentActivityComponent;
import com.clouddot.baipai.contract.IUrgentActivityContract;
import com.clouddot.baipai.http.entity.response.getArcticByIdResponse;
import com.clouddot.baipai.http.entity.response.getArcticListResponse;
import com.clouddot.baipai.http.entity.response.getBanPaiModelResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.environment;
import com.clouddot.baipai.module.UrgentActivityModule;
import com.clouddot.baipai.ui.adapter.UrgentAdapter;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.AlphaAndScaleTransformer;
import com.clouddot.baipai.util.viewUtil.ViewAnim;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.COMETOSET;
import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_ONE;
import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_THREE;

/**
 * Created by wxy on 2018/5/22.
 * 紧急模式的主界面
 */

public class UrgentActivity extends BaseActivity implements IUrgentActivityContract.IView, ViewPager.OnPageChangeListener, View.OnTouchListener {
    private List<getArcticListResponse.ariticInfo> mDataList = new ArrayList<>();
    private List<getArcticByIdResponse> mDataListInfos = new ArrayList<>();
    private ImageView[] mBottomImages;
    private UrgentAdapter adapter;
    private int currentViewPagerItem = -1;
    private boolean isAutoPlay = true;
    private boolean isLockSet = false;
    private boolean isLock = true;
    private boolean isActivity = false;
    private boolean isLive = true;
    @Inject
    IUrgentActivityContract.IPresenter mPresenter;

    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.indicator)
    LinearLayout indicator;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.imgloading)
    ImageView imgloading;


    @Override
    protected int getContentViewId() {
        if(Env.getAppContext().banPaiType == 0) {
            return R.layout.h_activity_urgent;
        }else{
            return R.layout.v_activity_urgent;
        }
    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(this);
        imgloading.startAnimation(loadingAnim);
        ThreadPoolFactory.getThread().execute(BanPaiModel);
    }

    @Override
    protected void initViews() {
        environment.getInstance().activities.add(this);
        DaggerIUrgentActivityComponent.builder().urgentActivityModule(new UrgentActivityModule(this)).build().inject(this);
        mPresenter.getArcticList("JJTZ", 1, 10);
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(UiVisibilityChangeListener);
        viewPager.setOnTouchListener(this);
        viewPager.setOnPageChangeListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mPresenter.getArcticList("JJTZ", 1, 10);
    }

    @Override
    protected void loadData() {

    }

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @OnClick({R.id.img_setting})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_setting:
                startActivityForResult(new Intent(UrgentActivity.this, SettingActivity.class), COMETOSET);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        switch (requestCode) {
            case COMETOSET:
                boolean flag = bundle.getBoolean("reSetIP", false);
                if (flag) {
                    startActivity(new Intent(UrgentActivity.this, AlaunchActivity.class));
                }
                break;
        }
    }

    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            /**
             * 更新紧急新闻列表
             */
            getArcticListResponse response = (getArcticListResponse) object;
            if (response.EntityList.isEmpty()) {
                fail(1, "紧急通知列表为空");
                return;
            }
            mDataList = response.EntityList;
            mDataListInfos.clear();
            if (!mDataList.isEmpty())
                for (getArcticListResponse.ariticInfo infoItem : mDataList)
                    mPresenter.getArcticById(infoItem.Id);

        } else if (flag == 2) {
            /**
             * 更新新闻文章item数据
             */
            getArcticByIdResponse response = (getArcticByIdResponse) object;
            mDataListInfos.add(response);
            if (mDataListInfos.size() == mDataList.size()) {
                loading.setVisibility(View.GONE);
                adapter = new UrgentAdapter(mDataListInfos, this);
                viewPager.setAdapter(adapter);
                viewPager.setPageMargin(30);
                viewPager.setOffscreenPageLimit(3);
                viewPager.setPageTransformer(false, new AlphaAndScaleTransformer());
                ThreadPoolFactory.getThread().execute(startAutoPlay);

                creatCriclePoint();
            }
        } else if (flag == 3) {
            /**
             * 判断当前的班牌模式
             */
            getBanPaiModelResponse response = (getBanPaiModelResponse) object;
            if (!response.Model.equals("Urgent")) {
                // 跳到加载页面
                startActivity(new Intent(UrgentActivity.this, AlaunchActivity.class));
                this.finish();
            }
        }

    }

    @Override
    public void fail(int flag, String errMsg) {
        ToastUtil.showToast(this, errMsg);
    }


    /***
     * startAutoPlay
     * 自动切换view
     */

    private Runnable startAutoPlay = new Runnable() {
        @Override
        public void run() {
            while (isLive) {
                try {
                    Thread.sleep(20000);
                    if (!isActivity) handler.sendEmptyMessage(MSG_ONE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * BanPaiModel 监听班牌模式
     */
    private Runnable BanPaiModel = new Runnable() {
        @Override
        public void run() {
            while (isLive) {
                try {
                    Thread.sleep(1000);
                    if (!isActivity) mPresenter.getBanPaiModel();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    };

    /**
     * 创建底部的小圆点
     */
    private void creatCriclePoint() {
        mBottomImages = new ImageView[mDataList.size()];
        for (int i = 0; i < mBottomImages.length; i++) {
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.setMargins(5, 0, 5, 0);
            imageView.setLayoutParams(params);
            if (i == 0) {
                imageView.setImageResource(R.drawable.indicator_select);
            } else {
                imageView.setImageResource(R.drawable.indicator_no_select);
            }
            mBottomImages[i] = imageView;
            indicator.addView(imageView);
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    if (isAutoPlay) {
                        ++currentViewPagerItem;
                        currentViewPagerItem = currentViewPagerItem % mDataList.size();
                        viewPager.setCurrentItem(currentViewPagerItem);
                    }
                    break;

                case MSG_THREE:
                    isLockSet = true;
                    if (isLock) {
                        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    } else {
                        int uiFlags = View.SYSTEM_UI_FLAG_VISIBLE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    }
                    isLockSet = false;
                    break;
            }
        }
    };


    /**
     * 监听底部的虚拟按键隐藏 对应handle 的 MSG_THREE
     */
    private View.OnSystemUiVisibilityChangeListener UiVisibilityChangeListener = new View.OnSystemUiVisibilityChangeListener() {
        @Override
        public void onSystemUiVisibilityChange(int visibility) {
            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                if (!isLockSet) {
                    handler.sendEmptyMessage(MSG_THREE);
                }
            }
        }
    };

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentViewPagerItem = position;
        if (mDataListInfos != null) {
            position %= mBottomImages.length;
            int total = mBottomImages.length;

            for (int i = 0; i < total; i++) {
                if (i == position) {
                    mBottomImages[i].setImageResource(R.drawable.indicator_select);
                } else {
                    mBottomImages[i].setImageResource(R.drawable.indicator_no_select);
                }
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isAutoPlay = false;
                break;
            case MotionEvent.ACTION_UP:
                isAutoPlay = true;
                break;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isActivity = false;
        isLive = true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivity = true;
        isLive = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isActivity = true;
        isLive = false;
    }
}
